import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import axios from "axios";
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeIndex.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginIndex.vue"),
  },
  {
    path: "/signup",
    name: "signup",
    component: () => import("../views/SignUp.vue"),
  },
  {
    path: "/column/:id",
    name: "column",
    component: () => import("../views/ColumnDetail.vue"),
  },
  {
    path:"/upload",
    name:'upload',
    component:()=>import("../views/PostDetail.vue")
  },
  {
    path: "/create",
    name: "create",
    component: () => import("../components/CreatePost.vue"),
  },
  {
    path: "/post/:id",
    name: "post",
    component: () => import("../views/PostDetail.vue"),
  },

];

const router = createRouter({
  history: createWebHistory(process.env.BASE_ULR),
  routes,
});

router.beforeEach((to, from, next) => {
  const { user, token } = store.state;
  const { redirectAlredyLogin, requiredLogin } = to.meta;
  if (!user.isLogin) {
    //没有登录的状态false
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      store
        .dispatch("fetchCurrentUser")
        .then(() => {
          if (redirectAlredyLogin) {
            next("/")
          } else {
            next()
          }
        })
        .catch((e) => {
          console.log(e);
          store.commit("logout")
          next("./login")
        })
    } else {
      if (requiredLogin) {
        next("/login")
      } else {
        next()
      }
    }
  } else {
    if (redirectAlredyLogin) {
      next("/")
    } else {
      next()
    }
  }
})

export default router
